﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>添加客户订单</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <style>
        body {
            padding: 15px;
            background: #f5f5f5;
        }
        .form-container {
            background: #fff;
            padding: 25px;
            border-radius: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,.1);
            max-width: 1400px;
            margin: 0 auto;
        }
        .layui-form-label {
            width: 80px;
            text-align: right;
            padding-right: 8px;
            font-size: 13px;
        }
        .layui-input-block {
            margin-left: 88px;
        }
        .required {
            color: #FF5722;
        }
        .form-buttons {
            text-align: center;
            margin-top: 25px;
            padding-top: 20px;
            border-top: 1px solid #e6e6e6;
        }
        .form-buttons .layui-btn {
            margin: 0 10px;
            min-width: 80px;
        }
        .layui-textarea {
            resize: vertical;
        }
        .quantity-container {
            display: flex;
            align-items: center;
        }
        .quantity-input {
            flex: 1;
        }
        .quantity-controls {
            display: flex;
            flex-direction: column;
            margin-right: 10px;
        }
        .quantity-btn {
            width: 30px;
            height: 19px;
            line-height: 17px;
            font-size: 12px;
            padding: 0;
            margin: 1px 0;
        }
        .search-btn {
            width: 40px;
            height: 38px;
            line-height: 38px;
            padding: 0;
            margin-left: 5px;
        }
    </style>
</head>
<body>
    <div class="form-container">
        <form class="layui-form" lay-filter="addForm" id="addForm">
            <!-- 第一行：产品信息 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 产品编号</label>
                        <div class="layui-input-block">
                            <div style="display: flex;">
                                <input type="text" name="productCode" placeholder="点击选择产品" class="layui-input" lay-verify="required" readonly>
                                <button type="button" class="layui-btn layui-btn-primary search-btn" id="selectProduct">
                                    <i class="layui-icon layui-icon-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 产品名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="productName" placeholder="自动填充" class="layui-input" lay-verify="required" readonly>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 第二行：产品规格 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md12">
                    <div class="layui-form-item">
                        <label class="layui-form-label">产品规格</label>
                        <div class="layui-input-block">
                            <input type="text" name="productSpec" placeholder="自动填充" class="layui-input" readonly>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 第三行：订单和客户编码 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 订单编码</label>
                        <div class="layui-input-block">
                            <div style="display: flex; align-items: center;">
                                <input type="text" name="orderCode" placeholder="请输入订单编码" class="layui-input" lay-verify="required" style="flex: 1;">
                                <div style="margin-left: 10px; white-space: nowrap;">
                                    <input type="checkbox" name="autoGenerate" title="自动生成" lay-filter="autoGenerate" style="margin-right: 5px;">
                                    <span style="font-size: 12px; color: #666;">自动生成</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">客户编码</label>
                        <div class="layui-input-block">
                            <div style="display: flex;">
                                <input type="text" name="customerCode" placeholder="点击选择客户" class="layui-input" readonly>
                                <button type="button" class="layui-btn layui-btn-primary search-btn" id="selectCustomer">
                                    <i class="layui-icon layui-icon-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 第四行：客户名称 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md12">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 客户名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="customerName" placeholder="自动填充" class="layui-input" lay-verify="required" readonly>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 第五行：日期信息 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 订货日期</label>
                        <div class="layui-input-block">
                            <input type="text" name="orderDate" placeholder="请选择订货日期" class="layui-input" lay-verify="required" id="orderDate">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 交货日期</label>
                        <div class="layui-input-block">
                            <input type="text" name="deliveryDate" placeholder="请选择交货日期" class="layui-input" lay-verify="required" id="deliveryDate">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 第六行：数量和单位 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 订货数量</label>
                        <div class="layui-input-block">
                            <div class="quantity-container">
                                <div class="quantity-controls">
                                    <button type="button" class="layui-btn layui-btn-primary quantity-btn" id="increaseBtn">+</button>
                                    <button type="button" class="layui-btn layui-btn-primary quantity-btn" id="decreaseBtn">-</button>
                                </div>
                                <input type="number" name="orderQuantity" value="1" class="layui-input quantity-input" lay-verify="required|number" min="1">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 单位</label>
                        <div class="layui-input-block">
                            <select name="unit" lay-verify="required">
                                <option value="">请选择</option>
                                <option value="个">个</option>
                                <option value="公斤">公斤</option>
                                <option value="克">克</option>
                                <option value="吨">吨</option>
                                <option value="米">米</option>
                                <option value="件">件</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 第七行：规格型号和质量要求 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">规格型号</label>
                        <div class="layui-input-block">
                            <input type="text" name="specModel" placeholder="请输入规格型号" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">质量要求</label>
                        <div class="layui-input-block">
                            <textarea name="qualityRequirements" placeholder="请输入质量要求" class="layui-textarea" rows="3"></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 按钮区域 -->
            <div class="form-buttons">
                <button type="submit" class="layui-btn" lay-submit lay-filter="confirmBtn">确定</button>
                <button type="button" class="layui-btn layui-btn-normal" id="generateProductionBtn">生成生产工单</button>
                <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
            </div>
        </form>
    </div>

    <script>
        layui.use(['form', 'laydate', 'layer'], function() {
            var form = layui.form;
            var laydate = layui.laydate;
            var layer = layui.layer;

            // 初始化日期选择器
            laydate.render({
                elem: '#orderDate',
                type: 'date',
                value: new Date()
            });

            laydate.render({
                elem: '#deliveryDate',
                type: 'date'
            });

            // 数量增减按钮事件
            $('#increaseBtn').on('click', function() {
                var input = $('input[name="orderQuantity"]');
                var currentVal = parseInt(input.val()) || 1;
                input.val(currentVal + 1);
            });

            $('#decreaseBtn').on('click', function() {
                var input = $('input[name="orderQuantity"]');
                var currentVal = parseInt(input.val()) || 1;
                if (currentVal > 1) {
                    input.val(currentVal - 1);
                }
            });

            // 产品选择按钮事件
            $('#selectProduct').on('click', function() {
                layer.open({
                    type: 2,
                    title: '产品选择',
                    area: ['900px', '650px'],
                    content: '/CustomerOrder/ProductInfoDilog',
                    maxmin: true,
                    success: function(layero, index) {
                        // 设置回调函数，供子页面调用
                        window.productSelectCallback = function(productData) {
                            // 填充产品信息到表单
                            $('input[name="productCode"]').val(productData.code);
                            $('input[name="productName"]').val(productData.name);
                            $('input[name="productSpec"]').val(productData.spec);
                            
                            // 关闭弹窗
                            layer.close(index);
                            
                            layer.msg('产品选择成功');
                        };
                    },
                    end: function() {
                        // 清理回调函数
                        window.productSelectCallback = null;
                    }
                });
            });

            // 自动生成编号开关事件
            form.on('checkbox(autoGenerate)', function(data) {
                var orderCodeInput = $('input[name="orderCode"]');
                
                if (data.elem.checked) {
                    // 开启自动生成
                    orderCodeInput.prop('readonly', true);
                    orderCodeInput.prop('placeholder', '自动生成中...');
                    
                    // 调用后端API生成编号
                    $.ajax({
                        url: '/CustomerOrder/GetCode',
                        type: 'GET',
                        data: { type: 'KD' },
                        success: function(response) {
                            if (response && response.success) {
                                orderCodeInput.val(response.data);
                                orderCodeInput.prop('placeholder', '自动生成');
                                layer.msg('编号生成成功', {icon: 1, time: 1000});
                            } else {
                                var errorMsg = response && response.message ? response.message : '生成编号失败';
                                layer.msg(errorMsg, {icon: 2, time: 2000});
                                // 生成失败时取消选中状态
                                data.elem.checked = false;
                                form.render('checkbox');
                                orderCodeInput.prop('readonly', false);
                                orderCodeInput.prop('placeholder', '请输入订单编码');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('生成编号失败:', error);
                            layer.msg('网络错误，生成编号失败', {icon: 2, time: 2000});
                            // 生成失败时取消选中状态
                            data.elem.checked = false;
                            form.render('checkbox');
                            orderCodeInput.prop('readonly', false);
                            orderCodeInput.prop('placeholder', '请输入订单编码');
                        }
                    });
                } else {
                    // 关闭自动生成
                    orderCodeInput.prop('readonly', false);
                    orderCodeInput.prop('placeholder', '请输入订单编码');
                    orderCodeInput.val('');
                    layer.msg('已关闭自动生成', {icon: 0, time: 1000});
                }
            });

            // 客户选择按钮事件
            $('#selectCustomer').on('click', function() {
                layer.open({
                    type: 2,
                    title: '客户选择',
                    area: ['1100px', '700px'],
                    content: '/CustomerOrder/CustomerShowDilog',
                    maxmin: true,
                    success: function(layero, index) {
                        // 设置回调函数，供子页面调用
                        window.customerSelectCallback = function(customerData) {
                            // 填充客户信息到表单
                            $('input[name="customerCode"]').val(customerData.code);
                            $('input[name="customerName"]').val(customerData.name);
                            
                            // 关闭弹窗
                            layer.close(index);
                            
                            layer.msg('客户选择成功');
                        };
                    },
                    end: function() {
                        // 清理回调函数
                        window.customerSelectCallback = null;
                    }
                });
            });

            // 表单提交
            form.on('submit(confirmBtn)', function(data) {
                layer.msg('正在保存订单...', {
                    icon: 16,
                    time: 2000
                });

                // 构建提交数据
                var formData = data.field;
                var submitData = {
                    productCode: formData.productCode,
                    productName: formData.productName,
                    productSpec: formData.productSpec || '',
                    orderCode: formData.orderCode,
                    customerCode: formData.customerCode || '', // 客户编码
                    customerName: formData.customerName,
                    orderDate: formData.orderDate,
                    deliveryDate: formData.deliveryDate,
                    orderQuantity: parseInt(formData.orderQuantity),
                    unit: formData.unit,
                    specModel: formData.specModel || '',
                    qualityRequirements: formData.qualityRequirements || '',
                    orderStatus: 0
                };

                // 调用后端API
                $.ajax({
                    url: '/CustomerOrder/AddCustomerOrder',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(submitData),
                    success: function(response) {
                        // 根据返回的success字段判断是否成功（注意字段名大小写）
                        if (response && (response.Success || response.success)) {
                            var orderId = response.Data || response.data;
                            var message = response.Message || response.message;
                            layer.msg('订单保存成功！订单ID：' + orderId, {
                                icon: 1,
                                time: 2000
                            }, function() {
                                // 跳转回查询页面
                                window.location.href = '/CustomerOrder/CustomerOrderQuery';
                            });
                        } else {
                            var errorMsg = (response && (response.Message || response.message)) ? (response.Message || response.message) : '未知错误';
                            layer.msg('保存失败：' + errorMsg, {
                                icon: 2,
                                time: 3000
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        var errorMsg = '网络错误，请稍后重试';
                        if (xhr.responseText) {
                            try {
                                var errorResponse = JSON.parse(xhr.responseText);
                                errorMsg = errorResponse.Message || errorMsg;
                            } catch (e) {
                                errorMsg = xhr.responseText;
                            }
                        }
                        
                        layer.msg(errorMsg, {
                            icon: 2,
                            time: 3000
                        });
                    }
                });

                return false;
            });

            // 生成生产工单按钮
            $('#generateProductionBtn').on('click', function() {
                // 先验证表单
                var formData = form.val('addForm');
                if (!formData.productCode || !formData.productName || !formData.orderCode || 
                    !formData.customerName || !formData.orderDate || !formData.deliveryDate || 
                    !formData.orderQuantity || !formData.unit) {
                    layer.msg('请填写完整信息后再生成生产工单', {icon: 2});
                    return;
                }

                layer.confirm('确定要生成生产工单吗？', {
                    icon: 3,
                    title: '提示'
                }, function(index) {
                    layer.msg('正在生成生产工单...', {
                        icon: 16,
                        time: 2000
                    });

                    // 模拟生成成功
                    setTimeout(function() {
                        layer.msg('生产工单生成成功！', {
                            icon: 1,
                            time: 1500
                        }, function() {
                            // 跳转回查询页面
                            window.location.href = '/CustomerOrder/CustomerOrderQuery';
                        });
                    }, 2000);
                    
                    layer.close(index);
                });
            });

            // 取消按钮
            $('#cancelBtn').on('click', function() {
                layer.confirm('确定要取消吗？未保存的数据将丢失。', {
                    icon: 3,
                    title: '提示'
                }, function(index) {
                    window.location.href = '/CustomerOrder/CustomerOrderQuery';
                    layer.close(index);
                });
            });

            // 渲染表单
            form.render();
        });
    </script>
</body>
</html>